<?php

/**
 * This is the model class for table "admin".
 *
 * The followings are the available columns in table 'admin':
 * @property string $id
 * @property string $username
 * @property string $password
 * @property string $lastlogin
 * @property string $salt
 * @property string $last_ip
 */
class Admin extends Base
{
    private $power = 'powerByMeng';   //版本，用于密码加密
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'admin';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('username', 'length', 'max'=>20),
			array('password', 'length', 'max'=>32),
			array('lastlogin, last_ip', 'length', 'max'=>10),
			array('salt', 'length', 'max'=>12),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, username, password, lastlogin, salt, last_ip', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
            'role'=>array(self::BELONGS_TO, 'Role', 'role_id','select'=>'name'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'username' => '用户名',
			'password' => '密码',
			'lastlogin' => '上次登录实际',
			'salt' => '盐',
			'last_ip' => '上次登录ip',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('lastlogin',$this->lastlogin,true);
		$criteria->compare('salt',$this->salt,true);
		$criteria->compare('last_ip',$this->last_ip,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Admin the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
     * 生成盐，默认12位
	*/
	public static function createSalt($len = 12) {
        $str = 'abcdefghijkmnpqrstuvwxyz0123456789ABCDEFGHIGKLMNPQRSTUVWXYZ';//设置被随机采集的字符串
        $rand = '';
        for($i=0; $i<$len-1; $i++){
            $rand .= $str[mt_rand(0, strlen($str)-1)];  //如：随机数为30  则：$str[30]
        }
        return $rand;
    }

    public function login($password) {
        if (empty($password) || !is_string($password)) {
            $this->addError('login','密码非法');
            return false;
        }
        if (!$this->verifyPassword($password)) {
            $this->addError('login','用户名或密码错误');
            return false;
        }
        $this->loginSuccess();
        return true;
    }

    public function logout() {
	    if (empty($this->username)) {
            $this->addError('logout','用户不存在或已经注销');
            return false;
        }
	    $ret = Yii::app()->session->remove('auth');
	    if (is_null($ret)) {
            $this->addError('logout','用户不存在或已经注销');
	        return false;
        }
	    return true;
    }

    /**
     * 登录成功之后，写入当前用户IP，当时时间，session
    */
    private function loginSuccess() {
        $ip = Yii::app()->request->userHostAddress;
        $this->last_ip = ip2long($ip);
        $this->lastlogin = time();
        $this->save();
        $this->writeSession(); //登录信息写入session
    }

    /**
     * 用户名、id、权限列写入session
    */
    private function writeSession() {
        $auth = array(
            'username' => $this->username,
            'id' => $this->id,
        );
        Yii::app()->session['auth'] = $auth;
    }

    /**
     * 判断登录密码是否正常
     * @param $password string 登录密码
     * @return bool 登录密码是否正确
    */
    private function verifyPassword($password) {
	    if (empty($password) || !is_string($password) || empty($this->username)) {
	        return false;
        }
	    $hash_password = $this->createPasswordHash($password);
	    return $hash_password == $this->password;
    }

    /**
     * 生成密码哈希值,
     * 必须药包含用户名和盐才能生成
     * @param string $password 密码明文
     * @return string 密码的哈希值
    */
    public function createPasswordHash($password) {
        if (empty($password) || !is_string($password)) {
            return '';
        }
        if (empty($this->username) || empty($this->salt)) {
            return '';
        }
        $salt = $this->salt;
        $power = $this->power;
        $username = $this->username;
        return md5(md5($power).md5($password).md5($username).md5($salt).md5($power));
    }

    /**
     * 创建用户
     * @param $data array 数据
     * @return bool  创建、修改成功/失败
     */
    public function modifyAdmin($data) {
        if (empty($this->id)) {
            $this->addError('username', '用户名不存在');
            return false;
        }
        if ($this->username === 'admin') {
            $this->addError('username', '系统默认用户不能修改');
            return false;
        }

        if (!empty($data['password'])) {
            $password = $data['password'];
            $this->salt = self::createSalt();
            $this->password = $this->createPasswordHash($password);
        }

        $this->role_id = $data['role_id'];
        return $this->save();
    }

    public function createAdmin($data) {
        if (empty($data['username'])) {
            $this->addError('username', '用户名不能为空');
            return false;
        }
        $same_admin = $this->findByAttributes(array('username'=> $data['username']));
        if ($same_admin !== null) {
            $this->addError('username', '用户名已经存在');
            return false;
        }
        $this->username = $data['username'];
        $this->salt = self::createSalt();
        $this->password = $this->createPasswordHash('88888888');
        $this->role_id = $data['role_id'];
        return $this->save();
    }

    /**
     * 删除用户
     * @return bool
    */
    public function remove() {
        if (empty($this->id)) {
            $this->addError('id', '用户不存在');
            return false;
        }
        if ($this->username === 'admin') {
            $this->addError('username', '系统默认用户无法删除');
            return false;
        }
        return $this->delete();
    }

    protected function pageListOpt(CDbCriteria $criteria) {
        $criteria->select = 'id,username,role_id';
    }
}
